<?php namespace Home\Model;

use Framework\Model\Model;

class User extends Model
{
	protected $table='user';

	public function reg()
	{
		if(empty($_POST['username']))
		{
			$this->error = '帐号输入错误';
			return false;
		}
		if(empty($_POST['password']))
		{
			$this->error = '密码输入错误';
			return false;
		}

		if($_POST['password']!=$_POST['password_c'])
		{
			$this->error = '密码不一至';
			return false;
		}

		if(strtoupper($_POST['code'])!=$_SESSION['code'])
		{
			$this->error = '验证码输入错误';
			return false;
		}
		if($this->where("username='{$_POST['username']}'")->select())
		{
			$this->error = '帐号已存在';
			return false;
		}

		$token = substr(md5(time()),0,10);
		$password = md5($_POST['password'].$token);

		$sql = "INSERT INTO user set username=? ,password=?,token=?";
		$data=[$_POST['username'],$password,$token];

		$this->execute($sql,$data);

		$id = $this->getInsertId();
		$_SESSION['id']=$id;
		return true;
	} 

	/**
	 * 登录
	 * @return [type] [description]
	 */
	public function login()
	{
		if(empty($_POST['username']))
		{
			$this->error = '帐号输入错误';
			return false;
		}
		if(empty($_POST['password']))
		{
			$this->error = '密码输入错误';
			return false;
		}
		if(!$user = $this->where("username='{$_POST['username']}'")->first())
		{
			$this->error = '帐号不存在';
			return false;
		}

		if(md5($_POST['password'].$user['token'])!=$user['password'])
		{
			$this->error ='密码错误';
			return false;
		}

		$_SESSION['id']=$user['id'];
		return true;
	}
}











